package com.ooc.formV1.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.oocl.formV1.dao.UserDao;
import com.oocl.formV1.pojo.User;
import com.oocl.formV1.util.DBUtil;

public class UserDaoImpl implements UserDao{

	@Override
	public int addUser(User user) {
		String sql = "insert into users(id, name, sal, birth, sex) values(userSeq.nextval, ?, ?, ?, ?)";
		Connection con=null;
		PreparedStatement pst = null;
		System.out.println(user.toString());
		int m = 0;
		try {
			con=DBUtil.createConnectionWithDataSource();
			pst = con.prepareStatement(sql);
			pst.setString(1, user.getName());
			pst.setDouble(2, user.getSal());
			pst.setDate(3, new java.sql.Date(user.getBirth().getTime()));
			pst.setString(4, user.getSex());
			m = pst.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(null, pst, null);
		}
		return m;
		
	}

	@Override
	public List<User> findAll() {
		List<User> list = new ArrayList<User>();
		String sql = "select * from users";
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		try {
			con=DBUtil.createConnectionWithDataSource();
			pst = con.prepareStatement(sql);
			
			rs = pst.executeQuery();
			while (rs.next()) {
				User user=new User(rs.getInt("id"), rs.getString("name"), rs.getDouble("sal"), new java.sql.Date(rs.getDate("birth").getTime()), rs.getString("sex"));
				list.add(user);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		finally{
			DBUtil.close(null, pst, rs);
		}
		return list;
	}

}
